import { ElMessageBox } from 'element-plus'
import {
  updateUserInfo,
  userSearch,
  deleteUserById,
  createUser,
  updateState,
  getAllUsers,
  uploadExcel
} from '@/services/roleCommon.js'
import { useRoleTitleCase, useRolePrefix } from '@/hooks/useRolePrefix.js'
import { binMsg } from '@/global/api.js'
import { formatNormalData } from '@/utils/formatDate.js'
import { findCMC } from '@/services/college.js'
import { selector3, filterList3, generateCascaderData } from '@/utils/cascaderUtil.js'
import { exportToExcel, processData } from '@/utils/utils.js'

const userManageModule = {
  namespaced: true,
  state() {
    return {
      // 用户相关
      adminList: [],
      adminCount: 0,
      teacherList: [],
      teacherCount: 0,
      studentList: [],
      studentCount: 0,
      // 教师和学生需要用到的，表单配置选项
      collegeList: [],
      collge_major_classes_list: []
    }
  },

  mutations: {
    changeAdminList(state, userList) {
      state.adminList = userList
    },
    changeAdminCount(state, count) {
      state.adminCount = count
    },
    changeTeacherList(state, userList) {
      state.teacherList = userList
    },
    changeTeacherCount(state, count) {
      state.teacherCount = count
    },
    changeStudentList(state, userList) {
      state.studentList = userList
    },
    changeStudentCount(state, count) {
      state.studentCount = count
    },
    changeCollegeList(state, list) {
      state.collegeList = list
    },
    changecollge_major_classes_list(state, list) {
      state.collge_major_classes_list = list
    },
    // 退出时清空state数据
    clearState(state) {
      state.adminList = []
      state.teacherList = []
      state.studentList = []
      state.collegeList = []
      state.collge_major_classes_list = []
    }
  },

  actions: {
    //* 获取学院、专业、班级列表，作为添加教师或学生的所属学院和班级选项的数据
    async getCollegeAndMajorAndClass({ commit }, payload) {
      const { data: res } = await findCMC()
      commit('changeCollegeList', [...res.data.data.collegeRes])
      // console.log(res)
      // 将数据修改成合适的格式交给 selector3 进行嵌套
      const newColleges = res.data.data.collegeRes.map((item) => {
        return { id: item.id, label: item.college_name, value: item.college_name }
      })
      const newMajors = res.data.data.majorRes.map((item) => {
        return { id: item.id, label: item.major_name, value: item.major_name, cid: item.cid }
      })
      const newClasses = res.data.data.classesgeRes.map((item) => {
        return { id: item.id, label: item.class_name, value: item.class_name, mid: item.mid }
      })
      const cascaderData = generateCascaderData(newColleges,newMajors,newClasses)
      // console.log(cascaderData);
      commit('changecollge_major_classes_list', cascaderData)
    },

    //* 根据编号、名称、学号、专业、学院查询用户数据（管理员、教师，教师）
    async searchUserAction({ commit, state, dispatch }, payload) {
      // console.log(payload)
      const { data: res } = await userSearch(payload)
      if (res.meta.status !== 200) return binMsg('error', res.meta.msg)
      // 修改对应用户列表和总数
      const name = useRoleTitleCase(payload.role)
      if (payload.label === 'name' || payload.label === 'major' || payload.label === 'college') {
        commit(`change${name}List`, res.data.list)
        commit(`change${name}Count`, res.data.total)
      } else {
        commit(`change${name}List`, [res.data.data])
        commit(`change${name}Count`, 1)
      }
      // console.log(res)
      // 如果学院管理中的学院列表为空，则调用获取学员列表
      if (state.collegeList.length === 0) {
        dispatch('getCollegeAndMajorAndClass')
      }
    },

    //* 修改用户信息
    async updateUserInfoAction({ commit, state }, payload) {
      // 处理时间格式
      if (payload.formData.admission_date) {
        payload.formData.admission_date = formatNormalData(payload.formData.admission_date)
      }
      // 如果是学生，修改了班级选项
      if (payload.role === 2) {
        if (payload.formData?.class.includes(',')) {
          const arr = payload.formData.class.split(',')
          payload.formData.college = arr[0]
          payload.formData.major = arr[1]
          payload.formData.class = arr[2]
        }
      }
      // console.log(payload.formData)
      const { data: res } = await updateUserInfo(payload.role, payload.formData)
      if (res.meta.status !== 200) return binMsg('error', res.meta.msg)
      // 修改列表中的对应用户信息
      const statName = useRolePrefix(payload.role) // 角色前缀-state
      const commitName = useRoleTitleCase(payload.role) // 角色前缀-commit

      const newUser = res.data.data // 新用户
      const userList = [...state[`${statName}List`]] // 原用户列表
      for (let i = 0; i < userList.length; i++) {
        if (userList[i].id === newUser.id) {
          userList[i] = newUser
        }
      }
      // console.log(newUser)
      commit(`change${commitName}List`, userList)
      binMsg('success', res.meta.msg)
    },

    //* 修改用户状态
    async updateUserState({ commit }, payload) {
      const { data: res } = await updateState(payload.role, payload.id)
      if (res.meta.status !== 200) return binMsg('error', res.meta.msg)
      binMsg('success', res.meta.msg)
    },

    //* 删除用户
    async deleteUserByIdAction({ commit, state }, payload) {
      console.log('deleteUserByIdAction:',payload);
      try {
        await ElMessageBox.confirm('确认删除该用户吗？', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          draggable: true
        })
        // 发送请求进行删除
        const { data: res } = await deleteUserById(payload.role, payload.id)
        if (res.meta.status !== 200) return binMsg('error', res.meta.msg)
        // 删除成功，修改列表和总数
        const stateName = useRolePrefix(payload.role)
        const mutationName = useRoleTitleCase(payload.role)
        const newList = state[`${stateName}List`].filter((item) => item.id !== payload.id)
        const newCount = state[`${stateName}Count`] - 1
        commit(`change${mutationName}List`, newList)
        commit(`change${mutationName}Count`, newCount)
        binMsg('success', res.meta.msg)
      } catch (e) {
        binMsg('info', '已取消')
      }
    },

    //* 添加用户
    async createUserAction({ commit, dispatch }, payload) {
      // console.log(payload)
      // 处理时间格式
      if (payload.formData.admission_date) {
        payload.formData.admission_date = formatNormalData(payload.formData.admission_date)
      }
      // 如果是学生，有班级选项
      if (payload.formData.class) {
        const arr = payload.formData.class.split(',')
        payload.formData.college = arr[0]
        payload.formData.major = arr[1]
        payload.formData.class = arr[2]
      }
      // console.log(payload.formData)
      const { data: res } = await createUser(payload.role, payload.formData)
      if (res.meta.status !== 200) return binMsg('error', res.meta.msg)
      binMsg('success', res.meta.msg)
      // 重新请求用户信息数据
      dispatch('searchUserAction', { role: payload.role, label: 'name', value: '' })
    },

    //* 将用户数据导出为excel文件
    async exportToExcelAction({ commit }, payload) {
      // 格式化好的 excel 用户数据列表
      let data = []
      // 属性映射对象
      let enNameToCnName = null
      // TODO 管理员处理
      if (payload.role === 0) {
        const { data: res } = await getAllUsers(payload.role)
        enNameToCnName = {
          id: 'ID',
          name: '姓名',
          identify: '编号',
          account: '账号',
          gender: '性别',
          phone: '手机号码',
          email: '邮箱'
        }
        data = processData(enNameToCnName, res.data.data)
      } else if (payload.role === 1) {
        // TODO 教师处理
        const { data: res } = await getAllUsers(payload.role)
        enNameToCnName = {
          id: 'ID',
          name: '姓名',
          identify: '编号',
          account: '账号',
          gender: '性别',
          phone: '手机号码',
          email: '邮箱',
          college: '所属学院'
        }
        data = processData(enNameToCnName, res.data.data)
      } else {
        // TODO 学生处理
        const { data: res } = await getAllUsers(payload.role)
        enNameToCnName = {
          id: 'ID',
          name: '姓名',
          stu_num: '学号',
          college: '所属学院',
          major: '所属专业',
          class: '所属班级',
          admission_date: '入学年份',
          gender: '性别',
          level: '层次',
          phone: '手机号码',
          email: '邮箱',
          college: '所属学院'
        }
        data = processData(enNameToCnName, res.data.data)
      }
      exportToExcel(payload.title, data)
      // console.log( data)
    },

    //* 上传excel文件，批量创建用户
    async createUsersAction({ commit,dispatch }, payload) {
      // console.log('createUsersAction:', payload);
      const { data: res } = await uploadExcel(payload.role, payload.formData)
      if (res.meta.status !== 200) return binMsg('error', res.meta.msg)
      binMsg('success', res.meta.msg)
      // 重新请求用户信息数据
      dispatch('searchUserAction', { role: payload.role, label: 'name', value: '' })
    }
  },
  getters: {
    // 返回用户列表
    userList(state) {
      return (role) => {
        const name = useRolePrefix(role)
        return state[`${name}List`]
      }
    },
    // 返回用户列表数量
    userListCount(state) {
      return (role) => {
        const name = useRolePrefix(role)
        return state[`${name}Count`]
      }
    },
    // 返回用户列表数据中的所有头像链接
    userAvatarSrcList(state) {
      return (role) => {
        const name = useRolePrefix(role)
        return state[`${name}List`].map((item) => {
          return item.avatar
        })
      }
    },
    collegeList(state) {
      return state.collegeList
    }
  }
}

export default userManageModule
